import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Dialog, Message, Button, Drawer } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column, ENUMS, toSelectDataSource } from './stores/definitions';
import DataForm from './components/DataForm';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import RegionTree from '@/components/biz/RegionTree';


const Station = () => {
  return (
    <TauPage className="page-container-2">
      <CityList />
      <OtherStation />
    </TauPage>
  );
};

const CityList = observer(() => {
  const { otherStationStore: store } = useStore();

  useEffect(() => { store.region = {}; }, []);

  return (
    <div className="left-panel" style={{ maxWidth: 180, minWidth: 180, padding: 10, borderRight: 'solid 1px var(--color-fill1-4)' }}>
      <RegionTree
        type={3}
        onRegion={(r) => {
          store.region = r;
        }}
      />
    </div>
  );
});

const OtherStation = observer(() => {
  const { otherStationStore: store } = useStore();
  const [companyData, setCompanyData] = useState([]);
  const [modal, setModal] = useState({
    show: false,
    record: {},
  });


  useEffect(() => {
    (async () => {
      const res = await store.getCompany({ search: { isOperating: true }, pg: { page: 0, size: 10 } });
      setCompanyData(res);
    })();
  }, []);

  const handleSearch = (params) => {
    const { companyId, ...searchArgs } = params.values;

    store.search = {
      companyId,
      ...searchArgs,
    };
  };

  const handleViewPlatform = (record) => {
    setModal({ show: 'view', record });
  };

  const handleEdit = (record) => {
    setModal({ show: 'edit', record });
  };

  const handleOnCancel = () => {
    setModal({ show: '', record: {} });
  };

  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS({ ...result }));
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleAddPlatform = async (result) => {
    Dialog.confirm({
      content: t`确定添加为平台站点吗？`,
      onOk: async () => {
        try {
          // 新加入站点信息
          const {
            companyId, companyName, kind, longLat,
            name, offAddress, onAddress, stationId, cityId } = toJS(result);
          const toggleSite = {
            companyId,
            cityId,
            companyName,
            stationId,
            stationName: name,
            description: '',
            link: '',
            longLat,
            onAddress,
            offAddress,
            kind,
            attachments: [],
          };
          _.unset(result, 'third');
          _.unset(result, 'cityId');
          _.unset(result, 'cityName');
          await store.create(toJS({ ...result, siteMapping: [toggleSite] }));
          Message.success({ content: t`添加成功` });
        } catch (e) {
          Message.error({ content: t`添加失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };


  const handleUpdateAllStation = async () => {
    try {
      await store.updateAllStation();
      Message.success({ content: t`同步成功` });
    } catch (error) {
      Message.error({ content: t`同步失败`, duration: 7000 });
      throw error;
    }
  };

  const handleDelete = async (result) => {
    Dialog.confirm({
      content: t`确定删除当前站点吗？`,
      onOk: async () => {
        try {
          await store.remove(result?.id);
          Message.success({ content: t`删除成功` });
        } catch (error) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw error;
        }
      },
    });
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        className="action-panel"
        onSearch={handleSearch}
        actions={[
          {
            title: t`同步承运商站点`,
            type: 'primary',
            onClick: handleUpdateAllStation,
          },
        ]}
        searchItems={[
          {
            name: 'companyId',
            type: 'select',
            props: {
              placeholder: t`公司名称`,
              dataSource: companyData,
              style: { width: 130 },
            },
          },
          {
            name: 'related',
            type: 'select',
            props: {
              placeholder: t`是否关联`,
              dataSource: ENUMS.RADIO_LIST,
              style: { width: 130 },
            },
          },
          {
            name: 'kinds',
            type: 'select',
            props: {
              placeholder: t`站点类型`,
              dataSource: toSelectDataSource(ENUMS.kind),
              style: { width: 360 },
              mode: 'multiple',
            },
          },
        ]}
      />
      <div className="content">
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('stationId', {}),
            column('companyName', {}),
            column('cityName', {}),
            column('areaName', {}),
            column('name', {}),
            column('kind', { width: 100 }),
            column('address', {}),
            column('longLat', {}),
            column('platformStation', {
              width: 200,
              cell: (v, __, other) => {
                return other.third.map((j, i, r) => (
                  <>
                    <Button type="primary" text onClick={() => handleViewPlatform(other)}>{j.name}</Button>
                    <br />
                  </>
                ));
              },
            }),
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 200,
              cell: (_, __, station) => {
                const funcMenu = [
                  {
                    title: '编辑',
                    onClick: () => handleEdit(station),
                  },
                  {
                    title: '添加平台站点',
                    onClick: () => handleAddPlatform(station),
                  },
                  {
                    title: '删除',
                    onClick: () => handleDelete(station),
                    color: 'red',
                    show: station?.third?.length === 0,
                  },
                ];
                return (
                  <>
                    <MoreFuncDropDown
                      dropdownItems={funcMenu}
                      maxShow={1}
                    />
                  </>
                );
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={modal.show === 'view' || modal.show === 'edit'}
        title={modal.show === 'view' ? t`查看站点` : t`编辑站点`}
        onClose={() => handleOnCancel()}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        <DataForm
          modal={modal.show}
          stationId={modal.record?.stationId}
          onCancel={handleOnCancel}
          data={modal.record}
          onSubmit={handleUpdate}
        />
      </Drawer>
    </TauPage>
  );
});

export default observer(Station);
